package com.heima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.reggie.bean.*;
import com.heima.reggie.dto.OrdersDto;
import com.heima.reggie.mapper.OrdersMapper;
import com.heima.reggie.service.*;
import com.heima.reggie.utils.BaseContext;
import com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.NotWritablePropertyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper mapper;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private ShoppingCartServcie shoppingCartServcie;
    @Autowired
    private OrderDetailService orderDetailService;
    /**
      * 分页查询
      * @param
      * @param
      * @return
      */
    @Override
    public IPage<OrdersDto> findPage(PageParam pageParam) {
        IPage<Orders> ordersPage = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(pageParam.getNumber()!=null,Orders::getNumber,pageParam.getNumber());
        if (pageParam.getBeginTime()!=null&&pageParam.getEndTime()!=null){
            lqw.between(Orders::getOrderTime,pageParam.getBeginTime(),pageParam.getEndTime());
        }
        lqw.orderByDesc(Orders::getOrderTime);
        IPage<Orders> ordersIPage = mapper.selectPage(ordersPage, lqw);
        List<Orders> records = ordersIPage.getRecords();
        List<OrdersDto> collect = records.stream().map((orders) -> {
            OrdersDto ordersDto = new OrdersDto();
            Long addressBookId = orders.getAddressBookId();
            AddressBook addressBook = addressBookService.getById(addressBookId);
        /*    System.out.println("-----------");
            System.out.println(addressBook.getId());*/
            //System.out.println(addressBook.getDetail());
            ordersDto.setAddressName(addressBook.getDetail());
            BeanUtils.copyProperties(orders, ordersDto);
            //System.out.println("------------");
            //System.out.println(ordersDto);
            return ordersDto;
        }).collect(Collectors.toList());
        System.out.println("------------");
        System.out.println(collect);
        IPage<OrdersDto> dtoIPage = new Page<>();
        dtoIPage.setRecords(collect);
        dtoIPage.setTotal(ordersIPage.getTotal());
        return dtoIPage;
    }
/**
  * 新增
  * @param
  * @param
  * @return
  */
    @Override
    public int add(Orders orders,long uid) {
        initOrdres(orders,uid);
        int insert = mapper.insert(orders);
        if (insert > 0) {
            int row1=0;
            List<ShoppingCart> carts = shoppingCartServcie.findByUid(uid);
          /*  carts.stream().map((cart)->{
                OrderDetail orderDetail = new OrderDetail();
                BeanUtils.copyProperties(cart,orderDetail);
                orderDetail.setOrderId(orders.getId());
                row1+= orderDetailService.add(orderDetail);
            });*/
            for (ShoppingCart cart : carts) {
                OrderDetail orderDetail = new OrderDetail();
                BeanUtils.copyProperties(cart,orderDetail);
                orderDetail.setOrderId(orders.getId());
                shoppingCartServcie.deleteBySid(cart.getId());
                row1+= orderDetailService.add(orderDetail);
            }
            return row1 == carts.size() ? 2 : 0;
        }
        return insert;
    }
/**
  * 根据用户id分页查询
  * @param
  * @param
  * @return
  */
    @Override
    public IPage<OrdersDto> findOrdersUserPage(PageParam pageParam,long uid) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>().eq(Orders::getUserId, uid).orderByDesc(Orders::getCheckoutTime);
        Page<Orders> page = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        Page<Orders> ordersPage = mapper.selectPage(page, queryWrapper);
        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> collect = records.stream().map((orders) -> {
            OrdersDto ordersDto = new OrdersDto();
            int i = orderDetailService.counByOid(orders.getId());
            ordersDto.setSumNum(i);
            BeanUtils.copyProperties(orders, ordersDto);
            return ordersDto;
        }).collect(Collectors.toList());
        IPage<OrdersDto> dtoIPage = new Page<>();
        dtoIPage.setRecords(collect);
        dtoIPage.setTotal(ordersPage.getTotal());
        return dtoIPage;
    }

    private void initOrdres(Orders orders,long uid) {
        orders.setNumber(UUID.randomUUID().toString().replace("-",""));
        orders.setStatus(1);
        orders.setUserId(uid);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(1);
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(
                addressBook.getProvinceName()!=null?addressBook.getProvinceName():""+
                addressBook.getCityName()!=null?addressBook.getCityName():""+
                addressBook.getDistrictName()!=null?addressBook.getDistrictName():""+
                        addressBook.getDetail()
                );
        orders.setUserName(userService.selectByUid(uid).getName());
        orders.setConsignee(addressBook.getConsignee());
    }
}
